//
//  PaperViewManager.m
//  ZYOnlineSchool
//
//  Created by 毕武侠 on 2017/2/27.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "PaperViewManager.h"

#import "PaperCollectionView.h"

#import "PaperCollectionViewCell.h"

@interface PaperViewManager () <didSelectCollectionDelegate>

@property (nonatomic, assign) NSUInteger index;
@property (nonatomic, assign) NSUInteger maxIndex;

@property (nonatomic, strong, readwrite) RACSignal *picSignal;       // 图片展示Signal
@property (nonatomic, strong, readwrite) RACSignal *modelSignal;     // 当前页model的Signal
@property (nonatomic, strong, readwrite) RACSignal *linkSignal;      // 链接点击Signal，暂时未实现
@property (nonatomic, strong, readwrite) RACSubject *submitSignal;   // 发送Signal

@property (nonatomic, strong) PaperCollectionView *view;
@property (nonatomic, strong) UIButton *nextBtn;
@property (nonatomic, strong) UIButton *lastBtn;

@end

@implementation PaperViewManager
@dynamic view;

- (void)setupConfigure {
    [super setupConfigure];
    
    self.view = [[PaperCollectionView alloc] initForPaperCollectionView];
    if (self.superView) {
        [self.superView addSubview:self.view];
    }
    
    [self loadSliderBtn];
    
    self.submitSignal = [RACSubject subject];
    self.view.didDatagate = self;
    // 设置数据赋值
    self.view.sourceData = self.datas;
    
    // 用户当前页的Model
    self.modelSignal = [[RACObserve(self.view, contentOffset) map:^id(id value) {
        CGFloat x = [value CGPointValue].x;
        self.index = (NSUInteger)(x / SCREEN_WIDTH);
        if (self.maxIndex == 0) {
            self.maxIndex = (NSUInteger)(self.view.contentSize.width / SCREEN_WIDTH);
        }
        if (self.index == 0) {
            self.lastBtn.hidden = YES;
        }else{
            self.lastBtn.hidden = NO;
        }
        self.lastBtn.enabled = self.index == 0 ? NO : YES;
        if (self.index == self.maxIndex-1) {
            self.nextBtn.hidden = YES;
        }else{
            self.nextBtn.hidden = NO;
        }
        self.nextBtn.enabled = self.index == self.maxIndex - 1 ? NO : YES;
        return [self getIndexModelAtPoint:self.index];
    }] distinctUntilChanged];
}

- (void)loadSliderBtn {
    self.lastBtn = [[UIButton alloc] initWithFrame:CGRectMake(12.0f, SCREEN_HEIGHT - 74, 32, 32)];
    self.nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 12 - 32, SCREEN_HEIGHT - 74, 32, 32)];


    [self.lastBtn setBackgroundImage:[UIImage imageNamed:@"箭头-left"] forState:UIControlStateNormal];
    [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"箭头-right"] forState:UIControlStateNormal];

    
    [self.lastBtn addTarget:self action:@selector(didLastAction:) forControlEvents:UIControlEventTouchUpInside];
    if (self.superView) {
        [self.superView addSubview:self.lastBtn];
    }
    
    [self.nextBtn addTarget:self action:@selector(didNextAction:) forControlEvents:UIControlEventTouchUpInside];
    if (self.superView) {
        [self.superView addSubview:self.nextBtn];
    }
}

- (void)didLastAction:(UIButton *)btn {
    if (self.index > 0) {
        [self.view setContentOffset:CGPointMake((self.index - 1) * SCREEN_WIDTH, 0) animated:YES];
    }
}

- (void)didNextAction:(UIButton *)btn {
    if (self.index < self.maxIndex - 1) {
        [self.view setContentOffset:CGPointMake((self.index + 1) * SCREEN_WIDTH, 0) animated:YES];
    }
}

- (void)setShowSendView:(BOOL)showSendView {
    _showSendView = showSendView;
    self.view.showSendView = showSendView;
}

- (void)setShowToolCard:(BOOL)showToolCard {
    _showToolCard = showToolCard;
    self.view.showToolCard = showToolCard;
}

- (void)setShowCardTitleView:(BOOL)showCardTitleView {
    _showCardTitleView = showCardTitleView;
    self.view.showCardTitleView = showCardTitleView;
}

// 根据当前页码value获得对应的model
- (PaperBaseModel *)getIndexModelAtPoint:(NSInteger)value {
    __block PaperBaseModel *indexModel = nil;
    
    __block NSInteger index = -1;
    [self.datas enumerateObjectsUsingBlock:^(PaperModuleModel *moduleModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if (moduleModel.showModule == YES) {
            index++;
        }
        if (index == value) {
            indexModel = moduleModel;
            *stop = YES;
        }
        
        [moduleModel.module_question enumerateObjectsUsingBlock:^(PaperBaseModel * model, NSUInteger idx, BOOL * _Nonnull stop) {
            index++;
            if (value == index) {
                indexModel = model;
                *stop = YES;
            }
        }];
    }];
    return indexModel;
}

#pragma mark - didSelectCollectionDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectIndexPath:(NSIndexPath *)indexPath { }

- (void)collectionView:(UICollectionView *)collectionView didActionIndexPath:(NSIndexPath *)indexPath infoData:(id)data {
    NSDictionary *dic = data;
    NSString *str = dic[@"action"];
    
    if ([str isEqualToString:@"select"]) {          // 点击选择选项
        [self didSelectAnswerAtIndexPath:indexPath WithData:data];
    } else if ([str isEqualToString:@"comment"]) {  // 点击评论
        [self didCommentAtIndexPath:indexPath WithData:data];
    } else if ([str isEqualToString:@"send"]) {     // 发送
        [self.submitSignal sendNext:dic[@"data"]];
    }else if([str isEqualToString:@"answer"]){      //问答题
        [self saveAnswerContentAtIndexpath:indexPath withData:data];
    }
}

//问答题处理
- (void)saveAnswerContentAtIndexpath:(NSIndexPath *)indexPath withData:(NSDictionary *)dic{
    NSString  *content = dic[@"contet"];
    PaperModuleModel *moduleModel = self.view.sourceData[indexPath.section];
    PaperAnswerModel *answerModel = moduleModel.module_question[indexPath.row];
    answerModel.user_content = content;
    
    [self setOptionWithData:@{@"user_content" : content} atIndexPath:indexPath];
//    int index = 0;
//        // 多选
//        PaperAnswerOptionModel *optionModel = answerModel.optionLayouts[index];
//        if (optionModel.type == PaperOptionTypeNormal) {    // 用户未选择过
//            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:index], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeSelect]} atIndexPath:indexPath];
//            answerModel.index++;
//        } else {
//            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:index], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeNormal]} atIndexPath:indexPath];
//            answerModel.index--;
//        }
    

    
}

// 点击选项功能，显示选项选中时的状态，和跳转到下一题
- (void)didSelectAnswerAtIndexPath:(NSIndexPath *)indexPath WithData:(NSDictionary *)dic {
    NSUInteger index = [dic[@"index"] integerValue];
    
    PaperModuleModel *moduleModel = self.view.sourceData[indexPath.section];
    PaperAnswerModel *answerModel = moduleModel.module_question[indexPath.row];
    
    if (answerModel.ques_model == 0) {       // 单选
        if (answerModel.index == NSNotFound) {
            // 用户尚未选择, 让index选中
            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:index], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeSelect]} atIndexPath:indexPath];
            answerModel.index = index;
            
            // 跳转到下一题
            [self moveToNextIndexPathAtIndexPath:indexPath];
        } else if (answerModel.index == index){  // 取消index的选择
            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:index], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeNormal]} atIndexPath:indexPath];
            answerModel.index = NSNotFound;
            // 不需要跳转
        } else {
            // 将上一次选择的变成normal
            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:answerModel.index ], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeNormal]} atIndexPath:indexPath];
            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:index], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeSelect]} atIndexPath:indexPath];
            answerModel.index = index;
            
            // 跳转到下一题
            [self moveToNextIndexPathAtIndexPath:indexPath];
        }
    } else {                                // 多选
        PaperAnswerOptionModel *optionModel = answerModel.optionLayouts[index];
        if (optionModel.type == PaperOptionTypeNormal) {    // 用户未选择过
            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:index], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeSelect]} atIndexPath:indexPath];
            answerModel.index++;
        } else {
            [self setOptionWithData:@{@"index" : [NSNumber numberWithUnsignedInteger:index], @"type" : [NSNumber numberWithUnsignedInteger:PaperOptionTypeNormal]} atIndexPath:indexPath];
            answerModel.index--;
        }
    }
}

- (void)setOptionWithData:(NSDictionary *)data atIndexPath:(NSIndexPath *)indexPath {
    PaperCollectionViewCell *cell = (PaperCollectionViewCell *)[self.view cellForItemAtIndexPath:indexPath];
    [cell didActionWithData:data];
}

- (void)moveToNextIndexPathAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section >= self.view.sourceData.count) {
        return;
    }
    
    NSIndexPath *nextIndexPath;
    PaperModuleModel *moduleModel = self.view.sourceData[indexPath.section];
    
    NSUInteger nextIndex = indexPath.row + 1;
    if (nextIndex >= moduleModel.module_question.count) {
        NSUInteger nextSection = indexPath.section + 1;
        if (nextSection == self.view.sourceData.count) {
            [self.view moveToFootView];
        } else if (nextSection > self.view.sourceData.count) {
            return;
        } else {
            PaperModuleModel *nextModuleModel = self.view.sourceData[indexPath.section + 1];
            if (nextModuleModel.showModule == YES) {
                // 跳转到next Head View
                [self.view moveToNextHeadAtIndexPath:indexPath];
            } else {
                nextIndexPath = [NSIndexPath indexPathForRow:0 inSection:nextSection];
                [self.view moveToIndexPath:nextIndexPath];
            }
        }
    } else {
        nextIndexPath = [NSIndexPath indexPathForRow:nextIndex inSection:indexPath.section];
        [self.view moveToIndexPath:nextIndexPath];
    }
}

// 点击评论功能
- (void)didCommentAtIndexPath:(NSIndexPath *)indexPath WithData:(NSDictionary *)dic {
    
}

// 答题卡点击跳转到相应题功能
- (void)setCardSelectSignal:(RACSignal *)cardSelectSignal {
    _cardSelectSignal = cardSelectSignal;
    
    [_cardSelectSignal subscribeNext:^(id x) {
        [self.view moveToIndexPath:x];
    }];
}

- (void)setModuleSelectSignal:(RACSignal *)moduleSelectSignal {
    _moduleSelectSignal = moduleSelectSignal;
    [_moduleSelectSignal subscribeNext:^(id x) {
        [self.view moveToCurrentHeadAtIndexPath:x];
    }];
}

@end
